#include "sg90.h"

#include <stdbool.h>
#include "TM4C123GH6PM.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/pin_map.h"
#include "driverlib/pwm.h"

#include "FreeRTOS.h"
#include "task.h"

#include "myPWM/myPWM.h"

static pwm_property_t sg90_pwm_prop;
void sg90_driver_init(void)
{
  sg90_pwm_prop.frequency = 50;
  sg90_pwm_prop.width = 500000;
  if (M1PWM6_Init(&sg90_pwm_prop))
    return;
}

void sg90_move(uint8_t degree)
{
  if (degree > 180)
    sg90_pwm_prop.width = 2500000;
  else
    sg90_pwm_prop.width = 500000 +  2000000 * degree / 180;
  uint32_t duty = (sg90_pwm_prop.width * (SysCtlClockGet() / sg90_pwm_prop.division)) / 1000000000; // 计算占空比
  PWMPulseWidthSet(PWM1_BASE, PWM_OUT_6, duty);                                                     // 配置PWM占空比
}

void sg90_test(void)
{
  for(uint8_t i = 0; i < 180; i++){
    sg90_move(i);
    vTaskDelay(10 / portTICK_PERIOD_MS);
  }
  for(uint8_t i = 180; i > 0; i--){
    sg90_move(i);
    vTaskDelay(10 / portTICK_PERIOD_MS);
  }
}
